package utils;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import java.util.LinkedHashMap;
import java.util.Properties;

public class RedisService {
    private static Jedis jedis;

    public Jedis getJedis() {
        return jedis;
    }
    public RedisService(Properties properties) {
        try {
            // 使用Nacos配置客户端获取Redis配置
            ConfigService configService = NacosFactory.createConfigService(properties);
            // 从Nacos服务器拉取指定的配置
            String javaVersion = configService.getConfig("garena-security.yml", "DEFAULT_GROUP", 50000);
            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
            JSONObject jsonObject = objectMapper.readValue(javaVersion, JSONObject.class);
            LinkedHashMap spring = (LinkedHashMap) jsonObject.get("spring");
            LinkedHashMap redis = (LinkedHashMap) spring.get("redis");

            String redisUrl;
            redisUrl = "redis://:" + redis.get("password") + "@" + redis.get("host") + ":" + redis.get("port");

            // 创建Jedis客户端
            jedis = new Jedis(redisUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getSe(String s){
        return jedis.get(s);
    }
    public static void setSe(String s,long st, String session){
        jedis.setex(s,st,session);
    }

    public static void deleteSession(String account) {
        jedis.del("garena-security:session:" + account);
    }

    public void createConnect() {
        // 连接到Redis服务器
        jedis.connect();
    }
}
